/**
 * @Description: 页面路由守卫组件
 * @Author: mofish
 * @Date: 2022-05-27
 * @LastEditTime: 2022-05-27
 * @LastEditors: mofish
 */
 import React from 'react'
 import { Navigate, useLocation, useNavigate } from 'react-router-dom'
 import { ReactElementType, MetaType, OneOfResType, BeforeRouteEnterType } from '../../types'
 import { getDataType } from '../../utils'
 
 let temp: ReactElementType | null = null
 
 function Guard (
   {
     element,
     meta,
     beforeRouteEnter
   }: {
     element: ReactElementType;
     meta: MetaType;
     beforeRouteEnter?: BeforeRouteEnterType;
   }
 ) {
   element = element || <></>
   meta = meta || {}
 
   const location = useLocation()
   const { pathname } = location
 
   const navigate = useNavigate()
 
   if (beforeRouteEnter) {
     // TODO 同一个组件切换不进行路由拦截处理  可能后期需要修改
     if (temp === element) {
       return element
     }
     const pathRes = beforeRouteEnter({ pathname, meta })
     if (getDataType(pathRes) === 'Promise') {
       (pathRes as Promise<OneOfResType>).then((res: OneOfResType) => {
         if (res && res !== pathname) {
           navigate(res, { replace: true })
         }
       })
     } else if (pathRes && typeof pathRes === typeof element ) {
       element = pathRes as ReactElementType
     } else if (pathRes && pathRes !== pathname) {
       element = <Navigate to={pathRes as string} replace={true} />
     }
   }
 
   temp = element
   return element
 }
 
 export default Guard